package com.xingmang.admin.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingmang.common.constant.PageEntity;
import com.xingmang.common.constant.ResponseData;
import com.xingmang.common.constant.ResultBean;
import com.xingmang.common.dto.admin.DicListDTO;
import com.xingmang.common.dto.admin.DicPageDTO;
import com.xingmang.common.dto.admin.DicSaveDTO;
import com.xingmang.common.vo.admin.DicPageVO;
import com.xingmang.common.vo.admin.DicVO;
import com.xingmang.db.entity.Dic;
import com.xingmang.db.service.DicDBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @auther: hansom
 * @Version: 1.0
 * @create 2023/6/20 17:02
 */
@Service
@Slf4j
public class DicService {

    @Resource
    private DicDBService dicDBService;

    public ResultBean<PageEntity<DicPageVO>> page(DicPageDTO dto) {
        Page<Dic> page = dicDBService.page(new Page<>(dto.getPagenum(), dto.getPagesize()),
                new LambdaQueryWrapper<Dic>()
                        .eq(StringUtils.isNotEmpty(dto.getDmlb()), Dic::getDmlb, dto.getDmlb())
                        .eq(StringUtils.isNotEmpty(dto.getDmz()), Dic::getDmz, dto.getDmz())
                        .like(StringUtils.isNotEmpty(dto.getDmmc()), Dic::getDmmc, dto.getDmmc()));
        List<DicPageVO> collect = page.getRecords().stream().map(dic -> {
            DicPageVO vo = BeanUtil.copyProperties(dic, DicPageVO.class);
            return vo;
        }).collect(Collectors.toList());
        PageEntity<DicPageVO> pageEntity = new PageEntity<>();
        pageEntity.setRecords(collect);
        return ResponseData.success(pageEntity);
    }

    public ResultBean save(DicSaveDTO dto) {
        Dic dic = BeanUtil.copyProperties(dto, Dic.class);
        if (StringUtils.isEmpty(dto.getFdmz())){
            dic.setFdmz("0");
        }
        dicDBService.save(dic);
        return ResponseData.success(null);
    }

    public ResultBean<List<DicVO>> list(DicListDTO dto) {
        List<Dic> list = dicDBService.list(new LambdaQueryWrapper<Dic>()
                .eq(Dic::getDmlb,dto.getDmlb())
                .eq(StringUtils.isNotEmpty(dto.getDmz()), Dic::getDmz, dto.getDmz())
                .eq(StringUtils.isEmpty(dto.getFdmz()), Dic::getFdmz, "0")
                .eq(StringUtils.isNotEmpty(dto.getFdmz()), Dic::getFdmz, dto.getFdmz())
                .eq(StringUtils.isNotEmpty(dto.getDmmc()), Dic::getDmmc, dto.getDmmc()));
        List<DicVO> dicVOS = BeanUtil.copyToList(list, DicVO.class);
        return ResponseData.success(dicVOS);
    }
}
